<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        :upload-before="uploadBefore"
        :upload-after="uploadAfter"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @search-reset="searchReset"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-del="rowDel"
        @row-save="create"
      >
        <template slot="menuLeft">
          <upload-card title="上传文件" @addFile="refreshChange()"></upload-card>
        </template>
        <template slot="imgUrlForm" slot-scope="scope">
          <div>
            <el-upload
              class="upload-file-manage"
              ref="upload"
              :headers="headers"
              action="/admin/sys-file/upload"
              :before-upload="uploadBefore"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary">文件上传</el-button>
              <div slot="tip" class="el-upload__tip">只支持jpg、png、gif、word文档、Excel表格、ppt格式文件，且大小不得超过50MB</div>
            </el-upload>
          </div>

        </template>
        <template
          slot="menu"
          slot-scope="scope">
          <el-button
            v-if="permissionList.downBtn"
            type="text"
            size="small"
            icon="el-icon-download"
            @click="download(scope.row,scope.index)">下载
          </el-button>
          <el-button
            v-if="permissionList.viewBtn"
            type="text"
            size="small"
            icon="el-icon-view"
            @click="viewPdf(scope.row,scope.index)">预览
          </el-button>
        </template>

      </avue-crud>
    </basic-container>
  </div>
</template>

<script>
import { delObj, fetchList } from '@/api/admin/sys-file'
import { tableOption } from '@/const/crud/admin/sys-file'
import { getStore } from '@/util/store'
import { mapGetters } from 'vuex'
import { handleDown,previewPdf } from '@/util/util'
import uploadCard from './upload'
import {matchType} from '@/filters'


export default {
  name: 'sys-file',
  components:{uploadCard},
  data() {
    return {
      searchForm: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,

      fileList:[],
      headers:{
        'Accept': 'application/json, text/plain, */*',
        'TENANT-ID': getStore({name: 'tenantId'}),
        'Authorization': 'Bearer ' + getStore({name: 'access_token'}),
      },
      doneSuccess: null,
      doneLoading: null,
      doneCount: 0,
    }
  },
  created() {
  },
  mounted: function() {
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.sys_file_add, true),
        delBtn: this.vaildData(this.permissions.sys_file_del, true),
        editBtn: this.vaildData(this.permissions.sys_file_edit, false),
        downBtn: this.vaildData(this.permissions.sys_file_down, true),
        viewBtn: this.vaildData(this.permissions.sys_file_view, true),
      }
    }
  },
  methods: {
    getList(page, params) {
      this.tableLoading = true
      fetchList(Object.assign({
        descs: 'create_time',
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm)).then(response => {
        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    rowDel: function(row, index) {
      var _this = this
      this.$confirm('是否确认删除文件 ' + row.original +'？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delObj(row.id)
      }).then(data => {
        _this.$message.success('删除成功')
        this.getList(this.page)
      })
    },
    searchChange(form, done) {
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    searchReset() {
      this.searchForm = {}
      this.page.currentPage = 1
      this.getList(this.page)
    },
    refreshChange() {
      this.searchForm = this.form
      this.getList(this.page)
    },
    sizeChange(pageSize){
      this.page.pageSize = pageSize
    },
    currentChange(current){
      this.page.currentPage = current
    },
    download: function(row, index) {
      handleDown(row.original, row.fileName, row.bucketName)
    },
    viewPdf(row, index){
      let type = matchType(row.fileName)
      if (type === 'word' || type === 'excel' || type === 'ppt' || type === 'pdf' || type === 'txt' || type === 'image'){
        previewPdf(row.bucketName,row.fileName)
      }else if (type === 'video' || type === 'radio'){
        this.$message.error('该文件暂不支持预览')
      }else{
        this.$message.error('该文件暂不支持预览')
      }

    },
    // uploadBefore(file,done,loading){
    uploadBefore(file){
      // let typeArr = ['.jpg','.png','.gif','.jpeg','.doc','.docx','.xls','.xlsx','.ppt','.pptx']
      let fileName = file.name
      let pos = fileName.lastIndexOf('.')
      let lastName = fileName.substring(pos, fileName.length)
      // if (!typeArr.includes(lastName.toLowerCase())) {
      //   this.$message.error('上传的附件格式不支持!')
      //   if (this.doneLoading)this.doneLoading()
      //   return false
      // }
      const isLt2M = file.size / 1024 / 1024 < 50;
      if (!isLt2M) {
        this.$message.error('上传附件大小不能超过 50MB!')
        if (this.doneLoading)this.doneLoading()
        return false
      }
      // done()
    },
    handleRemove(file, fileList) {
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].uid == file.uid) {
          this.fileList.splice(i, 1);
          break;
        }
      }
    },
    handlePreview(file) {
      console.log(file);
    },
    handleSuccess(response, file, fileList){
      if (response.code == 0){
        this.doneCount += 1
      }else{
        this.$message.error(file.name+'上传失败')
        this.doneLoading()
      }

      if (this.doneCount == fileList.length){
        this.$message.success('上传成功')
        this.doneSuccess()
        this.getList(this.page)
        this.doneCount = 0
      }
    },
    uploadAfter(res, done, loading) {
      // this.$message.success('上传成功')
      done()
      this.getList(this.page)
    },
    create(row, done, loading){
      this.doneSuccess = done
      this.doneLoading = loading
      this.$refs.upload.submit()

      // done()
    }
  }
}
</script>
<style>
  .upload-file-manage .el-upload{
    text-align: left;
  }
</style>

